package com.vpa.main;


import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Observable;
import java.util.Observer;


import android.util.SparseIntArray;

import com.vpa.graphics.GraphicsController;
import com.vpa.main.DataStore.Entry;
import com.vpa.main.MainActivity.UpdateElement;
import com.vpa.main.MainActivity.UpdateGauge;

public class Core implements Observer{
	public ListIterator<Entry> p_id_list;
	private SparseIntArray hm_key_pid = new SparseIntArray();
	private SparseIntArray hm_key_gauge = new SparseIntArray();
	public LinkedList<Integer> text_elements = new LinkedList<Integer>();
	GraphicsController gfx;
	PID_Store pid_store;
	MainActivity ac;
	int[] gauge_id;
	DataLogger logger;
	int text_area_id;
	
	public Core(GraphicsController gc,PID_Store pid_store, MainActivity ac){
		gauge_id = new int[120];
		this.gfx = gc;
		this.pid_store = pid_store;
		this.ac = ac;
		try
		{
			logger = new DataLogger();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
	
	public void addGauge(int pid,int gauge_id){
		hm_key_pid.put(pid, gauge_id);
		hm_key_gauge.put(gauge_id,pid);

	}
	
	
	/*returns the PID associated with the gauge*/
	public int removeGauge(int gauge_id_p){
		int pid = hm_key_gauge.get(gauge_id_p);
		hm_key_pid.delete(pid);
		hm_key_gauge.delete(gauge_id_p);
		return pid;
	}
	
	@Override
	public void update(Observable arg0, Object arg1) {
		Entry t = (Entry)arg1;
		logger.appendLine(t.p_id, true);
		int pid = Integer.parseInt(t.p_id.substring(2,4));
		if(text_elements.contains(pid)){
			UpdateElement runner = ac.new UpdateElement(text_area_id, hm_key_pid.get(pid), Double.toString(pid_store.get_real_value(t.p_id)), pid);
			ac.runOnUiThread(runner);

		}
		
		if(!t.p_id.contains("N") && !t.p_id.contains("R")){			
			UpdateGauge runner = ac.new UpdateGauge(hm_key_pid.get(Integer.parseInt(t.p_id.substring(2,4),16)),pid_store.get_real_value(t.p_id));
			ac.runOnUiThread(runner);
			return;
		}
	}


	public void addTextArea(int gauge_id2) {
		text_area_id = gauge_id2;
	}


	public void addTextElement(int pid,String title, String units) {
		int elementID = gfx.addTextAreaElement(text_area_id, title, units);
		hm_key_pid.put(pid, elementID);
		hm_key_gauge.put(elementID,pid);
		text_elements.add(pid);
	}


	public void clearTextArea() {
		text_area_id = -1;
		Iterator<Integer> it = text_elements.iterator();
		int text_pid;
		int g_id;
		while(it.hasNext()){
			text_pid = it.next();
		    g_id = hm_key_pid.get(text_pid);
			hm_key_gauge.delete(g_id);
			hm_key_pid.delete(text_pid);
		}
		
		text_elements.clear();
		
	}
	

}
